package com.lzp.wechat.controller;

import com.lzp.wechat.common.utils.WeChatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 接入微信服务器
 */
@RestController
@Api(tags = "微信验签接口")
public class SignatureController {

    /**
     * <验证消息的确来自微信服务器>
     * 开发者通过检验signature对请求进行校验（下面有校验方式）。若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，
     * 成为开发者成功，否则接入失败。加密/校验流程如下：
     * 1）将token、timestamp、nonce三个参数进行字典序排序
     * 2）将三个参数字符串拼接成一个字符串进行sha1加密
     * 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
     *
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return string & null
     */
    @GetMapping("/wechat")
    @ApiOperation(value = "验证消息的确来自微信服务器", notes = "验证消息的确来自微信服务器")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "signature", value = "微信加密签名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "timestamp", value = "时间戳", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "nonce", value = "随机数", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "echostr", value = "随机字符串", required = true, dataType = "String")
    })
    public String checkSignature(@RequestParam("signature") String signature,
                                 @RequestParam("timestamp") String timestamp,
                                 @RequestParam("nonce") String nonce,
                                 @RequestParam("echostr") String echostr) {
        // 验证sha1加密后的字符串是否与signature一致
        boolean flag = new WeChatUtil().validParams(signature, timestamp, nonce);
        // 如果一致，原样返回echostr参数内容
        if (flag) {
            return echostr;
        }
        return null;
    }

}
